package com.woniu.userassembly.component;

import com.woniu.userassembly.model.info.UserSeckillInfo;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class UserSeckillComponent {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    //参加秒杀团（抢购名额）
    public String joinSeckillTour(int userId,int travelNum,int seckillTourId){
        HashOperations operations = redisTemplate.opsForHash();
        //查询seckillTourId对应的团的缓存内，是否有当前用户的信息
        UserSeckillInfo userSeckillInfo = (UserSeckillInfo)operations.get("AfterSuccess"+seckillTourId,"userSeckillInfo"+userId);
        //判断用户是否抢购成功（抢购成功缓存里面有记录）
        if(null==userSeckillInfo){
            //获取seckillTourId对应的团的抢购成功名额
            int successNum = (Integer)operations.get("SeckillSuccess"+seckillTourId, seckillTourId);
            //用seckillTourId对抢购操作上锁
            RLock rLock = redissonClient.getLock(""+seckillTourId);
            boolean locked = rLock.tryLock();
            //如果当前是可操作状态，并且已成功抢购的名额+用户准备抢购的名额没超过规定数量，则可以抢购
            if(locked && successNum+travelNum<=20){
                //将用户准备抢购的名额
                operations.put("SeckillSuccess"+seckillTourId,seckillTourId,successNum+travelNum);
                //创建抢购成功后的用户信息
                UserSeckillInfo info = new UserSeckillInfo();
                info.setUserId(userId);
                info.setSeckillTourId(seckillTourId);
                info.setTravelNum(travelNum);
                info.setPayStuats("no");
                info.setSuccessTime(new Date().getTime());
                //将抢购成功的信息暂时添加到缓存
                operations.put("AfterSuccess"+seckillTourId,"userSeckillInfo"+userId,info);
                //设置缓存过期时间（1个半小时）
                redisTemplate.expire("AfterSuccess"+seckillTourId,90L, TimeUnit.MINUTES);
                //查询最新的抢购成功名额
                int newSuccessNum = (Integer)operations.get("SeckillSuccess"+seckillTourId, seckillTourId);
                log.info("{}：号用户抢到了,现在成功的人数{}",userId,newSuccessNum);
                log.info("允许解锁");
                //操作完成后解锁
                rLock.unlock();
                //返回抢购成功的消息
                return "抢购成功";
            }else {
                log.info("{}：号用户没抢到",userId);
                //返回抢购失败的消息
                return "当前抢购人数较多，请耐心等待";
            }
        }else{
            log.info("你已经抢购到名额，请尽快付款");
            //抢购成功后再次访问时，提示用户
            return "你已经抢购到名额，请尽快付款";
        }
    }

}
